<template>
  <div class="app-container">
    <!--选择仓库-->
    <SelectWarehouse ref="openSelectWarehouse"  @warehouseSelected="warehouseSelected"></SelectWarehouse>
    <SelectCustomer ref="openSelectCustomer"  @customerSelected="customerSelected"></SelectCustomer>
    <SelectWarehouseOutOrder ref="openSelectWarehouseOutOrder"  @warehouseOutOrderSelected="warehouseOutOrderSelected"></SelectWarehouseOutOrder>
    <!-- 增值服务收费/添加增值服务费用 -->
    <div class="detail-title-box">
      <span>详情信息</span>
    </div>
    <el-form ref="ruleForm" :model="ruleForm" label-width="120px" :inline="true" :rules="rules" :label-position="labelPosition">
      <el-form-item label="客户" prop="khmc">
        <el-input
            v-model="ruleForm.khmc"
            :disabled="true"
            style="width:225px"
        >
          <el-button slot="append" @click="customerSelect">选择</el-button>
        </el-input>
      </el-form-item>
      <el-form-item label="项目" prop="xm">
          <el-select
              v-model="ruleForm.xm"
              placeholder="请选择项目"
              clearable
              :loading="increServiceFeeItemLoading"
          >
              <el-option
                  v-for="item in itemIncreServiceFee"
                  :key="item.id"
                  :label="item.name"
                  :value="item.name"
              />
          </el-select>
      </el-form-item>
      <el-form-item label="发生日期" prop="rqid">
          <el-date-picker
              value-format="yyyy-MM-dd"
              v-model="ruleForm.rqid"
              type="date"
              placeholder="发生日期"
              style="width:90%">
          </el-date-picker>
      </el-form-item>
      <el-form-item label="收费标准" prop="bzdj">
        <el-input
            v-model="ruleForm.bzdj"
            placeholder="请输入收费标准"
            clearable
            @input="getAmount"
            style="width:235px"
            type="number"
            min="0"
        >
          <el-select
              slot="append"
              v-model="ruleForm.bz"
              placeholder="请选择"
              style="width:80px"
              @change="getAmount"
            >
              <el-option
                  v-for="item in unitType"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
          </el-select>
        </el-input>
      </el-form-item>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" plain size="mini" @click="warehouseSelect">选择库存</el-button>
          <el-button type="primary" plain size="mini" @click="warehouseOutSelect" >选择出仓单</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="ruleForm.inp"
        class="form-table"
      >
        <af-table-column label="操作" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
          <el-button
              size="mini"
              type="text"
              @click="handleRowDelete(scope.$index)"
          >删 除</el-button>
          </template>
        </af-table-column>
        <af-table-column label="客户条码" prop="sptm" width="150"/>
        <af-table-column label="仓库条码" prop="sptmc" width="150"/>
        <af-table-column label="柜号" prop="spgh" width="150"/>
        <af-table-column label="批号" prop="spbh" width="150"/>
        <af-table-column label="仓库" prop="spckmc" width="150"/>
        <af-table-column label="入仓日期" prop="ssrqid" width="150"/>
        <af-table-column label="收费吨数" prop="spsl" width="150">
          <template slot-scope="scope">
            <el-form-item :prop="'inp.' + scope.$index + '.spsl'" :rules="rules.inp.spsl">
              <el-input v-model="scope.row.spsl" size="mini" placeholder="请输入内容" @input="getAmountAndDigit(scope.$index)" type="number" min="0"/>
            </el-form-item>
          </template>
        </af-table-column>
        <af-table-column label="库存吨数" prop="spsl2" width="150"/>
        <af-table-column label="收费金额" prop="spje" width="150">
            <template slot-scope="scope">
                <el-form-item :prop="'inp.' + scope.$index + '.spje'" :rules="rules.inp.spje">
                  <el-input v-model="scope.row.spje" size="mini" placeholder="请输入内容" @input="getDigit(scope.$index)" type="number" min="0"/>
                </el-form-item>
            </template>
        </af-table-column>
        <af-table-column label="备注" prop="itbz" width="150">
            <template slot-scope="scope">
                <el-form-item>
                    <el-input v-model="scope.row.itbz" size="mini" placeholder="请输入内容"/>
                </el-form-item>
            </template>
        </af-table-column>
      </el-table>
    </el-form>
     <el-row type="flex" justify="center" :gutter="5" class="mt20">
      <el-col :span="1.5">
        <el-button type="primary" @click="increServiceFeeAddSubmit('ruleForm')">提交</el-button>
      </el-col>
       <el-col :span="1.5">
        <el-button @click="goBack">返回</el-button>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { increServiceFeeItem, increServiceFeeAdd } from "@/api/storage/commonGoods/increServiceFee"
import SelectCustomer from './selectCustomer.vue'
import SelectWarehouse from './selectWarehouse.vue'
import SelectWarehouseOutOrder from './selectWarehouseOutOrder.vue'
import { formatDate } from '@/utils'
import { AMOUNT_DIGIT } from '@/utils/constant'

export default {
  name: "IncreServiceFeeAdd",
  components: { SelectCustomer, SelectWarehouse, SelectWarehouseOutOrder },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      //右对齐
      labelPosition:"right",
      //收费项目加载
      increServiceFeeItemLoading:true,
      //弹窗状态
      openIncreServiceFeeAdd: false,
      //发生时间
      happenDate:'',
      //添加详情
      ruleForm:{
        khmc:"",
        bz: "元/次",
	      bzdj: "",
        rqid: "",
	      xm: "",
        inp:[]
      },
      unitType: [
        {label:"元/次", value:"元/次"},
        {label:"元/吨", value:"元/吨"}
      ],
      //校验
      rules: {
        bzdj:[{
          required: true,
          message: '收费标准不能为空',
          trigger: "blur"
        }],
        inp:{
          spsl: [
            {
              required: true,
              message: '收费吨数不能为空',
              trigger: "blur"
            },
            {
              required: true,
              validator: this.checkspsl,
              trigger: "blur"
            }
          ],
          spje: [
            {
              required: true,
              message: '收费金额不能为空',
              trigger: "blur"
            }
          ],
        }
      },
      //收费项目列表
      itemIncreServiceFee: [],
      //选择客户
      selectCustomerData:{},
    };
  },
  created() {
    const nowDate = formatDate(Date.now()).split(" ")[0]
    this.ruleForm.rqid = nowDate 
    this.getIncreServiceFeeItem()
  },
  methods: {
     /**获取收费项目 */
    getIncreServiceFeeItem() {
      this.increServiceFeeItemLoading=true
      increServiceFeeItem({}).then(response => {
        this.itemIncreServiceFee = response.data
        if(this.itemIncreServiceFee.length > 0) {
            this.ruleForm.xm = this.itemIncreServiceFee[0].name
        }
        this.increServiceFeeItemLoading=false
      });
    },
    /**添加增值服务费用 */
    increServiceFeeAddSubmit(formName) {
      this.$refs[formName].validate((valid, data) => {
        if(valid) {
          if(this.ruleForm.inp.length > 100) return this.$modal.msgError("货物行数不能大于100行！")
          if(this.ruleForm.inp.length === 0) return this.$modal.msgError("请先输入数据！")
          this.$modal.loading("数据正在提交中，请稍等...")
          increServiceFeeAdd(this.ruleForm).then(response => {
            this.$modal.closeLoading()
            this.$modal.msgSuccess('执行成功!')
            this.goIncreServiceFee()
          }).catch(()=> {
            this.$modal.closeLoading()
          })
        } else {
          for(let i in data) {
            const item = data[i]
            for(let j in item) {
              const message = item[j].message
              return this.$modal.msgError(message)
            }
          }
          return false
        }
      })
    },
    getDigit(index) {
      const r = this.ruleForm.inp[index]
      let spje = r.spje
      if(spje.indexOf('.')>0){
        spje=spje.slice(0,spje.indexOf('.')+3)
      }
      r.spje = spje
    },
    getAmountAndDigit(index) {
      const r = this.ruleForm.inp[index]
      let spsl = r.spsl
      if(spsl.indexOf('.')>0){
        spsl=spsl.slice(0,spsl.indexOf('.')+7)
      }
      r.spsl = spsl
      this.getAmount()
    },
    /** 获取收费金额*/
    getAmount() {
      const inp = this.ruleForm.inp
      let bzdj = this.ruleForm.bzdj
      if(bzdj.indexOf('.')>0){
        bzdj=bzdj.slice(0,bzdj.indexOf('.')+ 3)
      }
      this.ruleForm.bzdj = bzdj
      if(inp.length > 0) {
        for(let i in inp) {
          if(this.ruleForm.bz == "元/次") {
           this.$set(inp[i], "spje", bzdj)
          } else if(this.ruleForm.bz == "元/吨") {
            if(inp[i].spsl || inp[i].spsl == 0) {
              this.$set(inp[i], "spje", parseFloat(inp[i].spsl*bzdj).toFixed(AMOUNT_DIGIT))
            }
          }
        }
      }
    },
    /** 添加行删除*/
    handleRowDelete(index) {
      this.ruleForm.inp.splice(index, 1)
    },
    /**选择客户 */
    customerSelect() {
      this.$refs.openSelectCustomer.open()
    },
    /**选择仓库 */
    warehouseSelect() {
      if(!this.ruleForm.khmc) return this.$modal.msgError("请先选择客户！")
      const inp = this.ruleForm.inp
      this.$refs.openSelectWarehouse.open(inp, this.selectCustomerData.spkhmcid)
    },
    /**选择出仓单 */
    warehouseOutSelect() {
        this.$refs.openSelectWarehouseOutOrder.open()
    },
    /**选择出仓单返回 */
    warehouseOutOrderSelected(data) {
      if(data) {
        for(let i in data) {
          this.$set(data[i], "itbz", "")
          this.$set(data[i], "spsl", data[i].spsl2)
          this.ruleForm.inp.push(data[i])
        }
        this.getAmount()
      }
    },
    /**选择仓库返回 */
    warehouseSelected(data) {
      if(data) {
        for(let i in data) {
          this.$set(data[i], "itbz", "")
          this.ruleForm.inp.push(data[i])
        }
        this.getAmount()
      }
    },
    /**选择用户返回 */
    customerSelected(data) {
      this.selectCustomerData = data
      const {inp=[],spkhmc:khmc} = data
      this.ruleForm = {...this.ruleForm,khmc,inp}
    },
    /**验证收费吨数 */
    checkspsl(rule, value, callback) {
      const a = rule.field.split('.')
      const index = a[1]
      const spsl2 = parseFloat(this.ruleForm.inp[index].spsl2)
      if(spsl2 < value) {
        callback("收费吨数不可超过库存吨数")
      } else {
        callback()
      }
    },
     //跳回增值服务收费页
    goIncreServiceFee() {
      this.$tab.closePage(this.$route)
      this.$router.push({name:"IncreServiceFee", params: {refresh:true}})
    },
     /** 重置数据 */
    reset(vm) {
      Object.assign(vm.$data, vm.$options.data())
    },
     /**返回不刷新 */
    goBack() {
      this.$router.push({name:"IncreServiceFee"})
    },
  }
};
</script>
